package qdu.edu.cn.liu.filter;

import java.util.HashMap;
import java.util.HashSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GetHyperLink {
    private final HashMap<String, HashSet<String>> wordsAndHyperlinks = new HashMap<>();

    public HashMap<String, HashSet<String>> getWordsAndHyperlinks() {
        return wordsAndHyperlinks;
    }

    /**
     * 用于从一个字符串中提取出图片超链接
     *
     * @param content 含有图片超链接的网页源码（字符串）
     * @return 返回一个字符串，图片超链接以空格隔开
     */
    public String pattern(String content) {
        StringBuilder stringBuilder = new StringBuilder();
        Pattern pattern = Pattern.compile("https:[a-zA-Z0-9./&_\\-\\\\=,]+\\.jpg"); // 过滤掉含有%的URL
        Matcher matcher;
        String[] split = content.split(" ");

        for (String string : split) {
            matcher = pattern.matcher(string);
            while (matcher.find()) {
                stringBuilder.append(matcher.group()).append(" ");
            }
        }

        return stringBuilder.toString().replaceAll("\\\\", "");
    }

    /**
     * 该方法可以多次调用，然后调用getWordsAndHyperlinks方法获取
     *
     * @param content 网页的源代码
     * @param words   查询的关键字
     */
    public void pattern(String content, String words) {
        HashSet<String> hyperlinks = getHyperlinks(words);

        Pattern pattern = Pattern.compile("https:[a-zA-Z0-9./&_\\-\\\\=,]+jpg"); // 过滤掉含有%的URL
        Matcher matcher;
        String[] split = content.split(" ");

        for (String string : split) {
            matcher = pattern.matcher(string);
            while (matcher.find()) {
                hyperlinks.add(matcher.group().replaceAll("\\\\", ""));
            }
        }
    }

    /**
     * 根据words获取wordsAndHyperlinks中的hyperlinks，如果不存在，就创建，并存入wordsAndHyperlinks
     * @param words 查询的字符串（汉字词语）
     * @return hyperlinks
     */
    private HashSet<String> getHyperlinks(String words) {
        HashSet<String> hyperlinks;
        if ((hyperlinks = wordsAndHyperlinks.get(words)) == null) {
            hyperlinks = new HashSet<>();
            wordsAndHyperlinks.put(words, hyperlinks);
        }

        return hyperlinks;
    }
}
